import 'package:custom_widgets/screen_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart';
import 'package:mi_mang_flutter/model/public/menu_model.dart';
import 'package:mi_mang_flutter/res/dimens.dart';
import 'package:mi_mang_flutter/res/menu.dart';
import 'package:mi_mang_flutter/res/styles.dart';
import 'package:mi_mang_flutter/routers/fluro_navigator.dart';
import 'package:mi_mang_flutter/utils/dialog_util.dart';
import 'package:mi_mang_flutter/utils/image_utils.dart';
import 'package:mi_mang_flutter/utils/toast_util.dart';
import 'package:mi_mang_flutter/utils/utils.dart';
import 'package:share_plus/share_plus.dart';

/// 分享弹出层小部件
class WidgetShareDialog extends StatefulWidget {
  WidgetShareDialog({
    Key? key,
    required this.shareModel,
  }) : super(key: key);

  /// 分享的对象
  final WeChatShareModel shareModel;

  @override
  _WidgetShareDialog createState() => _WidgetShareDialog();
}

class _WidgetShareDialog extends State<WidgetShareDialog> {
  // 分享菜单按钮,可自定义拓展
  late List<MenuModel> _items;

  // 显示行数(用户控制分享弹出层的高度)
  late int _crossAxisCount;

  late WeChatShareModel _shareModel;

  String? _shareUrl;

  @override
  void initState() {
    super.initState();

    _initShareItemsOfType();
  }

  /// 初始化分享数据
  _initShareItemsOfType() {
    _shareModel = widget.shareModel;

    // 分享按钮(可根据分享类型初始化为不同的值)
    _items = Menu.shareMenus;

    // 获取分享链接or分享文本
    switch (_shareModel.runtimeType) {
      case WeChatShareTextModel:
        var model = _shareModel as WeChatShareTextModel;
        _shareUrl = model.source;
        // 如果是纯文本分享时,移除浏览器打开选项
        _items.removeWhere((item) => item.menuTag == 4);
        break;
      case WeChatShareMiniProgramModel:
        var model = _shareModel as WeChatShareMiniProgramModel;
        _shareUrl = model.webPageUrl;
        break;
      case WeChatShareImageModel:
        var model = _shareModel as WeChatShareImageModel;
        _shareUrl = "";
        if (model.source.localImagePath is String) {
          _shareUrl = model.source.localImagePath;
        }
        break;
      case WeChatShareMusicModel:
        var model = _shareModel as WeChatShareMusicModel;
        _shareUrl = model.musicUrl;
        break;
      case WeChatShareVideoModel:
        var model = _shareModel as WeChatShareVideoModel;
        _shareUrl = model.videoUrl;
        break;
      case WeChatShareWebPageModel:
        var model = _shareModel as WeChatShareWebPageModel;
        _shareUrl = model.webPage;
        break;
      default:
    }
    // 4到8之间显示两行,超过8也是单行显示(可滚动)
    // 超过8行时可进行分类,需另外处理
    _crossAxisCount = (_items.length > 4 && _items.length <= 8) ? 2 : 1;
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(Dimens.gapDp15),
      child: Material(
        borderRadius: BorderRadius.all(Radius.circular(Dimens.gapDp15)),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: EdgeInsets.only(top: Dimens.gapDp20),
              child: Text(
                "分享到",
                style: Theme.of(context).textTheme.titleLarge,
              ),
            ),
            Gaps.vGap15,
            SingleChildScrollView(
              scrollDirection:
                  _items.length > 8 ? Axis.horizontal : Axis.vertical,
              child: Container(
                // 控制分享层高度
                height: ScreenUtil.screenWidthDp! / 4 * _crossAxisCount,
                child: Wrap(
                  children: _getListItem(),
                ),
              ),
            ),
            Gaps.vGap10,
          ],
        ),
      ),
    );
  }

  List<Widget> _getListItem() {
    return _items.map(
      (item) {
        // 控制每个元素的大小为屏幕的1/4
        return SizedBox(
          width: ScreenUtil.screenWidthDp! / 4,
          height: ScreenUtil.screenWidthDp! / 4,
          child: _buildItem(item),
        );
      },
    ).toList();
  }

  Widget _buildItem(MenuModel item) {
    return Material(
      color: Colors.transparent,
      child: Ink(
        child: InkWell(
          borderRadius: new BorderRadius.circular(8.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              loadImage(item.image, width: 36.0, height: 36.0),
              Gaps.vGap10,
              Text(
                item.title!,
                maxLines: 1,
                style: Theme.of(context).textTheme.bodyMedium,
              )
            ],
          ),
          onTap: () {
            NavigatorUtils.goBack(context);
            _share(item);
          },
        ),
      ),
    );
  }

  _share(MenuModel item) {
    switch (item.menuTag) {
      // 微信好友
      // 分享至朋友圈
      // 微信收藏
      case 1:
      case 2:
      case 3:
        // 判断是否安装微信
        Fluwx().isWeChatInstalled.then((val) {
          if (val) {
            _wixinShare(item.menuTag);
          } else {
            Toast.showInfo("没有安装微信");
          }
        });
        break;
      // 浏览器中打开
      case 4:
        Utils.launchURL(_shareUrl ?? '');
        break;
      // 复制链接
      case 5:
        if (_shareUrl != null) {
          Clipboard.setData(ClipboardData(text: _shareUrl ?? ''));
          Toast.showInfo("已复制到剪切板");
        } else {
          Toast.showWarn("复制内容为空");
        }
        break;
      // 更多
      case 100:
        _systemShare();
        break;
      default:
    }
  }

  /// 微信分享
  _wixinShare(int? tag) {
    WeChatScene? scene = _shareChatScene(tag);
    late WeChatShareModel shareModel;

    /// 根据类型创建分享模型(由于外部创建的分享模型中WeChatScene为final)
    /// 导致这里的模型需要全部手动重新创建,仅仅只是为了修改外部出传入模型的scene属性
    switch (_shareModel.runtimeType) {
      case WeChatShareTextModel:
        var model = _shareModel as WeChatShareTextModel;
        shareModel = WeChatShareTextModel(
          model.source,
          title: model.title,
          description: model.description,
          scene: scene!,
          messageExt: model.messageExt,
          messageAction: model.messageAction,
          mediaTagName: model.mediaTagName,
        );
        break;
      case WeChatShareMiniProgramModel:
        var model = _shareModel as WeChatShareMiniProgramModel;
        shareModel = WeChatShareMiniProgramModel(
          webPageUrl: model.webPageUrl,
          miniProgramType: model.miniProgramType,
          userName: model.userName,
          path: model.path,
          title: model.title,
          description: model.description,
          // thumbnail: model.thumbnail,
          withShareTicket: model.withShareTicket,
          // hdImagePath: model.hdImagePath,
          messageExt: model.messageExt,
          messageAction: model.messageAction,
          mediaTagName: model.mediaTagName,
        );
        break;
      case WeChatShareImageModel:
        var model = _shareModel as WeChatShareImageModel;
        shareModel = WeChatShareImageModel(
          model.source,
          title: model.title,
          description: model.description,
          // thumbnail: model.thumbnail,
          scene: scene!,
          messageExt: model.messageExt,
          messageAction: model.messageAction,
          mediaTagName: model.mediaTagName,
        );
        break;
      case WeChatShareMusicModel:
        var model = _shareModel as WeChatShareMusicModel;
        shareModel = WeChatShareMusicModel(
          musicUrl: model.musicUrl,
          musicLowBandUrl: model.musicLowBandUrl,
          musicDataUrl: model.musicDataUrl,
          musicLowBandDataUrl: model.musicLowBandDataUrl,
          title: model.title,
          description: model.description,
          // thumbnail: model.thumbnail,
          scene: scene!,
          messageExt: model.messageExt,
          messageAction: model.messageAction,
          mediaTagName: model.mediaTagName,
        );
        break;
      case WeChatShareVideoModel:
        var model = _shareModel as WeChatShareVideoModel;
        shareModel = WeChatShareVideoModel(
          videoUrl: model.videoUrl,
          videoLowBandUrl: model.videoLowBandUrl,
          title: model.title,
          description: model.description,
          // thumbnail: model.thumbnail,
          scene: scene!,
          messageExt: model.messageExt,
          messageAction: model.messageAction,
          mediaTagName: model.mediaTagName,
        );
        break;
      case WeChatShareWebPageModel:
        var model = _shareModel as WeChatShareWebPageModel;
        shareModel = WeChatShareWebPageModel(
          model.webPage,
          title: model.title,
          description: model.description,
          // thumbnail: model.thumbnail,
          scene: scene!,
          messageExt: model.messageExt,
          messageAction: model.messageAction,
          mediaTagName: model.mediaTagName,
        );
        break;
      default:
    }
    Fluwx().share(shareModel);
  }

  /// 点击的分享类型(好友,朋友圈,收藏), 用于设置分享类别
  WeChatScene? _shareChatScene(int? tag) {
    WeChatScene? scene;
    switch (tag) {
      // 微信好友
      case 1:
        scene = WeChatScene.session;
        break;
      // 分享至朋友圈
      case 2:
        scene = WeChatScene.timeline;
        break;
      // 微信收藏
      case 3:
        scene = WeChatScene.favorite;
        break;
      default:
    }
    return scene;
  }

  /// 系统分享,目前只支持文本or链接
  _systemShare() {
    if (_shareUrl != null) {
      final RenderBox box = context.findRenderObject() as RenderBox;
      Share.share(
        _shareUrl!,
        sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size,
      );
    }
  }

  @override
  void dispose() {
    DialogUtil.isShowDialog = false;
    super.dispose();
  }
}
